package server.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import server.demo.dto.ApiResponse;
import server.demo.dto.OrderDTO;
import server.demo.dto.TicketDTO;
import server.demo.dto.TicketPurchaseRequest;
import server.demo.dto.TransferTicketPurchaseRequest;
import server.demo.dto.ticket.RefundTicketRequest;
import server.demo.dto.ticket.RescheduleTicketRequest;
import server.demo.service.TicketService;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/v1/tickets")
@CrossOrigin(origins = "*")
public class TicketController {
    
    @Autowired
    private TicketService ticketService;
    
    // 管理员功能 - 使用admin前缀避免路由冲突
    @GetMapping("/admin/orders")
    public ApiResponse<List<OrderDTO>> getAllOrders() {
        try {
            List<OrderDTO> orders = ticketService.getAllOrders();
            return ApiResponse.success(orders);
        } catch (Exception e) {
            return ApiResponse.error("获取订单列表失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/purchase")
    public ApiResponse<OrderDTO> purchaseTickets(@Valid @RequestBody TicketPurchaseRequest request) {
        try {
            OrderDTO order = ticketService.purchaseTickets(request);
            return ApiResponse.success("购票成功", order);
        } catch (Exception e) {
            return ApiResponse.error("购票失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/orders/user/{userId}")
    public ApiResponse<List<OrderDTO>> getOrdersByUserId(@PathVariable Long userId) {
        try {
            List<OrderDTO> orders = ticketService.getOrdersByUserId(userId);
            return ApiResponse.success(orders);
        } catch (Exception e) {
            return ApiResponse.error("获取订单列表失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/orders/{orderId}")
    public ApiResponse<OrderDTO> getOrderById(@PathVariable Long orderId) {
        try {
            Optional<OrderDTO> order = ticketService.getOrderById(orderId);
            if (order.isPresent()) {
                return ApiResponse.success(order.get());
            } else {
                return ApiResponse.error("订单不存在");
            }
        } catch (Exception e) {
            return ApiResponse.error("获取订单信息失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/user/{userId}")
    public ApiResponse<List<TicketDTO>> getTicketsByUserId(@PathVariable Long userId) {
        try {
            List<TicketDTO> tickets = ticketService.getTicketsByUserId(userId);
            return ApiResponse.success(tickets);
        } catch (Exception e) {
            return ApiResponse.error("获取票务列表失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/orders/{orderId}/cancel")
    public ApiResponse<Void> cancelOrder(@PathVariable Long orderId) {
        try {
            ticketService.cancelOrder(orderId);
            return ApiResponse.success("订单取消成功", null);
        } catch (Exception e) {
            return ApiResponse.error("取消订单失败: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/orders/{orderId}")
    public ApiResponse<Void> deleteOrder(@PathVariable Long orderId) {
        try {
            ticketService.deleteOrder(orderId);
            return ApiResponse.success("订单删除成功", null);
        } catch (Exception e) {
            return ApiResponse.error("删除订单失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/refund")
    public ApiResponse<Void> refundTicket(@Valid @RequestBody RefundTicketRequest request) {
        try {
            ticketService.refundTicket(request);
            return ApiResponse.success("退票成功", null);
        } catch (Exception e) {
            return ApiResponse.error("退票失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/reschedule")
    public ApiResponse<OrderDTO> rescheduleTicket(@Valid @RequestBody RescheduleTicketRequest request) {
        try {
            OrderDTO newOrder = ticketService.rescheduleTicket(request);
            return ApiResponse.success("改签成功", newOrder);
        } catch (Exception e) {
            return ApiResponse.error("改签失败: " + e.getMessage());
        }
    }
    
    // ========== 管理员票务管理接口 ==========
    
    @GetMapping
    public ApiResponse<List<TicketDTO>> getAllTickets(
            @RequestParam(required = false) String trainNumber,
            @RequestParam(required = false) String passengerName,
            @RequestParam(required = false) String status) {
        try {
            List<TicketDTO> tickets = ticketService.getAllTickets(trainNumber, passengerName, status);
            return ApiResponse.success(tickets);
        } catch (Exception e) {
            return ApiResponse.error("获取票务列表失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/{ticketId}")
    public ApiResponse<TicketDTO> getTicketById(@PathVariable Long ticketId) {
        try {
            Optional<TicketDTO> ticket = ticketService.getTicketById(ticketId);
            if (ticket.isPresent()) {
                return ApiResponse.success(ticket.get());
            } else {
                return ApiResponse.error("票务不存在");
            }
        } catch (Exception e) {
            return ApiResponse.error("获取票务信息失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{ticketId}/cancel")
    public ApiResponse<Void> cancelTicket(@PathVariable Long ticketId) {
        try {
            ticketService.cancelTicket(ticketId);
            return ApiResponse.success("票务取消成功", null);
        } catch (Exception e) {
            return ApiResponse.error("取消票务失败: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/{ticketId}")
    public ApiResponse<Void> deleteTicket(@PathVariable Long ticketId) {
        try {
            ticketService.deleteTicket(ticketId);
            return ApiResponse.success("票务删除成功", null);
        } catch (Exception e) {
            return ApiResponse.error("删除票务失败: " + e.getMessage());
        }
    }
    
    @PostMapping("/transfer/purchase")
    public ApiResponse<OrderDTO> purchaseTransferTickets(@Valid @RequestBody TransferTicketPurchaseRequest request) {
        try {
            OrderDTO order = ticketService.purchaseTransferTickets(request);
            return ApiResponse.success("换乘票务购买成功", order);
        } catch (Exception e) {
            return ApiResponse.error("购买换乘票务失败: " + e.getMessage());
        }
    }
}